package com.test.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.test.database.*;

/**
 * Servlet implementation class login_svr
 */
public class login_svr extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public final String currentUser = "currentUser";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public login_svr() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		final String key = "hasLogin";
		DataBase db = new DataBase();
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/test";
		String dataBaseUser  = "root";
		String rootPassword = "wei";
		boolean bCon = db.connectdb(driver, url, dataBaseUser, rootPassword);
		
		HttpSession session = request.getSession();
        response.setContentType("text/html; charset=UTF-8");
        ServletContext sc = getServletContext();
        RequestDispatcher rd = null;
		if(bCon)
		{
			boolean bSel = db.select("userinfo", username, password);
			if(bSel) {
				session.setAttribute(key, "hasLogined");
		        request.setAttribute(key, "success");
		        session.setAttribute(currentUser, username);
		        rd = sc.getRequestDispatcher("/viewImage.jsp");//
		        rd.forward(request, response);
			}
			else {

		        request.setAttribute(key, "false");
		        rd = sc.getRequestDispatcher("/login.jsp");
		        rd.forward(request, response);
			}
		}
	}
}
